package models

import (
	"api01/util"
	"errors"
	"github.com/astaxie/beego/orm"
	"golang.org/x/crypto/bcrypt"
)

type User struct {
	Id       int
	Name     string
	Account  string
	Password string
	Type   uint8
	Status   uint8
	CreateAt string
	UpdateAt string
}

const (
	USER_STATUS_REVIEW = iota //审核中
	USER_STATUS_PASS          //通过
	USER_STATUS_STOP          //停用

	USER_TYPE_ORIDINARY = 0   //普通用户
	USER_TYPE_ADMIN = 1		  //管理员
)


func init() {
	orm.RegisterModel(new(User))
}
//登录
func Login(account, password string) (string, error) {
	o := orm.NewOrm()
	user := new(User)
	err := o.QueryTable("user").Filter("account",account).One(user)
	if err != nil {
		return "", errors.New("账号不存在")
	}

	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	if err != nil {
		return "", errors.New("账号密码错误")
	}
	switch user.Status {
	case USER_STATUS_REVIEW:
		return "", errors.New("账号审核中")
	case USER_STATUS_PASS:
		claims := util.Claims{UserId: user.Id,UserType:user.Type}
		token, success := util.CreateToken(&claims)
		if !success {
			return "", errors.New("TOKEN创建失败")
		}
		return token,nil
	case USER_STATUS_STOP:
		return "", errors.New("账号已停用")
	default:
		return "", errors.New("账号异常")
	}
}

//注册
func Register(user *User) error {
	//密码加密
	password, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	user.Password = string(password)

	o := orm.NewOrm()
	//验证重复
	count, _ := o.QueryTable("user").Filter("account", user.Account).Count()
	if count > 0 {
		return errors.New("该账号已注册")
	}

	//插入数据
	_, err := o.Insert(user)
	if err != nil {
		return errors.New("注册失败")
	}

	return nil
}

//修改密码
func ChangePassword(account, password, newPassword string) error {
	o := orm.NewOrm()
	user := new(User)
	err := o.QueryTable("user").Filter("account", account).One(user)
	if err != nil {
		return errors.New("账号不存在")
	}
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	if err != nil {
		return errors.New("账号密码错误")
	}
	//新密码加密
	newPasswordEnc, _ := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
	user.Password = string(newPasswordEnc)
	_, err = o.Update(user)
	if err != nil {
		return errors.New("修改失败")
	}
	return nil
}